from django.shortcuts import render
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status
import base64, pickle

from . import constants
from goods.models import SKU
from . import serializers
from .serializers import CartSelectAllSerializer
# Create your views here.


class CartView(APIView):
    """
    购物车数据的增删改查
    """

    # 重写perform_authentication方法， 让用户无论登录与否都可以进来这个视图, 不让他执行request user方法
    def perform_authentication(self, request):

        pass

    def post(self, request):
        """新增"""
        # 新建序列化器对象
        serializer = serializers.CartSerializer(data=request.data)
        # 校验
        serializer.is_valid(raise_exception=True)
        # 读取校验之后的数据
        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']

        # 判断用户是否登录
        # request.user:用户登录，就会获取到用户信息， 反之会抛出异常或匿名用户
        try:
            user = request.user
        except Exception:
            user = None
        # user.is_authenticated:判断用户不是匿名用户
        # 用户已登录, 操作redis
        if user and user.is_authenticated:
            # 创建连接redis数据库的对象
            redis_conn = get_redis_connection('carts')
            # 创建管道， 优化redis操作
            pl = redis_conn.pipeline()
            # 操作hash数据类型， 用来存储哪个用户的哪件商品数量
            # hincrby():实现增量计算， 根据key值来判断是累加还是赋值
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 存储该商品是否勾选
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            # 执行
            pl.execute()
            # 响应结果
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:
            # 用户未登录， 操作cookie
            cart_str = request.COOKIES.get('cart')
            if cart_str:  # str字符串
                # 表示用户之前在未登录情况下操作过购物车
                # cart_str.encode()                                     # 二进制字符串
                # base64.b64decode(cart_str.encode())                     # 二进制字节
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))  # 字典
            else:
                # 表示用户从未在未登录的情况下操作购物车
                cart_dict = {}

            # 将前端传入的sku_id, count, selected存入到cookie中
            if sku_id in cart_dict:
                origin_count = cart_dict[sku_id]['count']
                count += origin_count

            # 将累加或者最新的count保存到字典中
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 将购物车数据由字典转换成字符串写入到cookie中
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 创建响应对象
            response = Response(serializer.data, status=status.HTTP_201_CREATED)

            # 将购物车数据写入到cookie中
            response.set_cookie('cart', cookie_cart_str, max_age=constants.CART_COOKIE_EXPIRES)

            # 返回响应对象
            return response

    def get(self, request):
        """查询"""

        # 判断用户是否登录
        # request.user:用户登录，就会获取到用户信息， 反之会抛出异常或匿名用户
        try:
            user = request.user
        except Exception:
            user = None
        # user.is_authenticated:判断用户不是匿名用户
        # 用户已登录, 操作redis
        if user and user.is_authenticated:
            # 创建连接redis数据库的对象
            redis_conn = get_redis_connection('carts')
            # 查询所有的购物车数据
            redis_cart = redis_conn.hgetall('cart_%s' % user.id)  # 二进制字典
            # 查询哪些商品被勾选   cart_selected = [sku_id, sku_id, ......]
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis_cart和cart_selected整合到cart_dict中， 实现格式的统一， 方便后续查询sku信息
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected  # 当sku_id 在cart_selected中， 返回True
                }
        else:
            # 用户未登录， 操作cookie
            cart_str = request.COOKIES.get('cart')
            if cart_str:  # str字符串
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))  # 字典
            else:
                # 表示用户从未在未登录的情况下操作购物车
                cart_dict = {}
        # 根据cart_dict查询所有的商品id
        sku_ids = cart_dict.keys()
        # 根据所有的sku_ids,查询出对应的sku信息
        skus = SKU.objects.filter(id__in=sku_ids)

        # 为了既能输出sku信息， 又能输出count和selected， 需要将他们追加到sku中
        for sku in skus:
            sku.count = cart_dict[sku.id]['count']
            sku.selected = cart_dict[sku.id]['selected']

        # 创建序列化器对象， 调用序列化器输出商品信息
        serializer = serializers.CartSKUSerializer(skus, many=True)
        # 响应数据
        return Response(serializer.data)


    def put(self, request):
        """修改"""
        # 新建序列化器对象
        serializer = serializers.CartSerializer(data=request.data)
        # 校验
        serializer.is_valid(raise_exception=True)
        # 读取校验之后的数据
        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']

        # 判断用户是否登录
        # request.user:用户登录，就会获取到用户信息， 反之会抛出异常或匿名用户
        try:
            user = request.user
        except Exception:
            user = None
        # user.is_authenticated:判断用户不是匿名用户
        # 用户已登录, 操作redis
        if user and user.is_authenticated:
            # 创建连接redis数据库的对象
            redis_conn = get_redis_connection('carts')
            # 创建管道， 进行优化redis操作
            pl = redis_conn.pipeline()
            # 修改商品数量, 使用幂等接口设计方案， 只做覆盖， 不做增量计算
            pl.hset('cart_%s' % user.id, sku_id, count)
            # 修改商品是否勾选
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                # 如果前端传入得是false， 我们只需要将sku_id在列表中移除即可， 表示未勾选
                pl.srem('selected_%s' % user.id, sku_id)

            # 执行管道
            pl.execute()

            # 响应结果
            return Response(serializer.data)
        else:
            # 用户未登录， 操作cookie
            cart_str = request.COOKIES.get('cart')
            if cart_str:  # str字符串
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))  # 字典
            else:
                # 表示用户从未在未登录的情况下操作购物车
                cart_dict = {}
            # 使用幂等方式， 覆盖写入新的数据
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 将购物车数据由字典转换成字符串写入到cookie中
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 创建响应对象
            response = Response(serializer.data)

            # 将购物车数据写入到cookie中
            response.set_cookie('cart', cookie_cart_str, max_age=constants.CART_COOKIE_EXPIRES)

            # 返回响应对象
            return response

    def delete(self, request):
        """删除"""
        # 创建序列化器对象
        serializer = serializers.CartDeleteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 获取校验后的sku_id
        sku_id = serializer.validated_data.get('sku_id')
        # 判断用户是否登录
        # request.user:用户登录，就会获取到用户信息， 反之会抛出异常或匿名用户
        try:
            user = request.user
        except Exception:
            user = None
        # user.is_authenticated:判断用户不是匿名用户
        # 用户已登录, 操作redis
        if user and user.is_authenticated:
            # 创建连接redis数据库的对象
            redis_conn = get_redis_connection('carts')
            # 管道
            pl = redis_conn.pipeline()
            # 删除某一条记录
            pl.hdel('cart_%s' % user.id, sku_id)
            # 移除勾选标记
            pl.srem('selected_%s' % user.id, sku_id)
            # 执行管道
            pl.execute()
            # 响应204, 因为数据已经删除，只响应状态码
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            # 用户未登录， 操作cookie
            cart_str = request.COOKIES.get('cart')
            if cart_str:  # str字符串
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))  # 字典
            else:
                # 表示用户从未在未登录的情况下操作购物车
                cart_dict = {}
            response = Response(status=status.HTTP_204_NO_CONTENT)
            if sku_id in cart_dict:
                del cart_dict[sku_id]

            # 将删除某些数据的购物车数据字典重新写入到cookie中
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('cart', cookie_cart_str, constants.CART_COOKIE_EXPIRES)

            return response


# 购物车是否全选  /cart/selection/
class CartSelectAllView(APIView):
    # 重写perform_authentication方法， 让用户无论登录与否都可以进来这个视图, 不让他执行request user方法
    def perform_authentication(self, request):
        pass

    def put(self, request):

        serializer = CartSelectAllSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        selected = serializer.validated_data['selected']

        # 判断用户是否登录
        # request.user:用户登录，就会获取到用户信息， 反之会抛出异常或匿名用户
        try:
            user = request.user
        except Exception:
            user = None
        # user.is_authenticated:判断用户不是匿名用户
        # 用户已登录, 操作redis
        if user and user.is_authenticated:
            # 创建连接redis数据库的对象
            redis_conn = get_redis_connection('carts')
            cart = redis_conn.hgetall('cart_%s' % user.id)
            sku_id_list = cart.keys()
            if selected:
                # 全选
                redis_conn.sadd('selected_%s' % user.id, *sku_id_list)
            else:
                # 取消全选
                redis_conn.srem('selected_%s' % user.id, *sku_id_list)
            return Response({'message': 'OK'})
        else:
            # 用户未登录， 操作cookie
            cart_str = request.COOKIES.get('cart')
            response = Response({'message': 'OK'})
            if cart_str:  # str字符串
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))  # 字典
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected

                # 将字典转成字符串
                cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('cart', cookie_cart_str, constants.CART_COOKIE_EXPIRES)
            return response


